package org.summerframework.component.security.oauth.util;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.summerframework.component.httpclient.HttpClientUtil;
import org.summerframework.component.httpclient.HttpParam;
import org.summerframework.component.httpclient.HttpResult;
import org.summerframework.component.security.oauth.OAuthResultCode;
import org.summerframework.component.security.oauth.exception.HttpClientException;
import org.summerframework.component.security.oauth.exception.JsonParsingException;

/**
 * HttpClientFinshUtil
 *
 * @author 石超
 * @date 2016/3/29
 */
public class HttpClientFinshUtil {
    public static JSONObject finsh(HttpParam httpParam) {
        return finsh(httpParam, null);
    }

    public static JSONObject finsh(HttpParam httpParam, String charset) {
        try {
            HttpResult result = HttpClientUtil.request(httpParam);

            if (!result.isSuccess()) {
                throw new HttpClientException(OAuthResultCode.ILLEGAL_ARGUMENT, "httpclient request error: " + result.getErrMsg());
            }

            if (charset == null) {
                return JSONObject.parseObject(result.getContext());
            } else {

                return JSONObject.parseObject(result.getContext(charset));
            }
        } catch (JSONException e) {
            throw new JsonParsingException(OAuthResultCode.ILLEGAL_ARGUMENT, "json parsing error: ", e);
        } catch (Exception e) {
            throw new HttpClientException(OAuthResultCode.ILLEGAL_ARGUMENT, "httpclient request error: ", e);
        }
    }
}

